package com.znsd.exam.controllor;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.ibatis.annotations.Param;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.znsd.entitys.Chapter;
import com.znsd.entitys.ClassInfo;
import com.znsd.entitys.Course;
import com.znsd.entitys.ExamPaperInfo;
import com.znsd.entitys.ExamSubjectMiddleInfo;
import com.znsd.entitys.GradeInfo;
import com.znsd.entitys.SpecialtyInfo;
import com.znsd.entitys.Subjectinfo;
import com.znsd.entitys.Users;
import com.znsd.exam.service.SpecialtyService;
import com.znsd.exam.service.SubjectService;
import com.znsd.exam.util.SubjectImportUtil;
import com.znsd.study.service.WorkService;
import com.znsd.utils.FormatUtil;

import freemarker.template.Configuration;
import freemarker.template.Template;


@Controller
public class SubjectControllor {
	@Autowired
	private WorkService ws;
	@Autowired
	private SubjectService subjectInfoService;
	@Autowired
	private SpecialtyService specialtyService;
	private GradeInfo grade = new GradeInfo();
	private Subjectinfo subject = new Subjectinfo();
	private Course course = new Course();
	private ExamPaperInfo examPaper = new ExamPaperInfo();

	static List<Subjectinfo> myList=new ArrayList<Subjectinfo>();//我的集合
	private Logger logger = Logger.getLogger(SubjectControllor.class);

	@RequestMapping(value = "/subjects", method = RequestMethod.GET)
	public ModelAndView getTeachers(@RequestParam(value = "subjectId", required = false) Integer subjectId,
			@RequestParam(value = "courseId", required = false) Integer courseId,
			@RequestParam(value = "gradeId", required = false) Integer gradeId,
			@RequestParam(value = "startPage", required = false, defaultValue = "1") Integer startPage,
			@RequestParam(value = "pageShow", required = false, defaultValue = "10") Integer pageShow,
			@RequestParam(value = "handAdd", required = false) Integer handAdd,
			@RequestParam(value = "examPaperId", required = false) Integer examPaperId, HttpSession session) {
		logger.info("查询试题集合");

		ModelAndView model = new ModelAndView();
		model.setViewName("admin/subjects");
		Map<String, Object> map = new HashMap<String, Object>();
		// 计算当前查询起始数据索引
		int startIndex = (startPage - 1) * pageShow;
		System.out.println(subject);
		map.put("subject", subject);
		map.put("startIndex", startIndex);
		map.put("pageShow", pageShow);
		List<Subjectinfo> subjects = subjectInfoService.getSubjects(map);
		for (int i = 0; i < subjects.size(); i++) {
			subjects.get(i).setChapter(specialtyService.getPointsListId(subjects.get(i).getChapterid()));
			subjects.get(i).setSpecialty(specialtyService.getPointsListId(subjects.get(i).getSpecialtyid()));
		}
		model.addObject("subjects", subjects);

		// 获取试题总量
		int subjectTotal = subjectInfoService.getSubjectTotal();
		System.out.println(subjectTotal);
		// 计算总页数
		int pageTotal = 1;
		if (subjectTotal % pageShow == 0)
			pageTotal = subjectTotal / pageShow;
		else
			pageTotal = subjectTotal / pageShow + 1;
		model.addObject("pageTotal", pageTotal);
		model.addObject("pageNow", startPage);
		return model;
	}

	@RequestMapping(value = "/addSubject", method = RequestMethod.GET)
	public ModelAndView subjecAdd() {
		ModelAndView model = new ModelAndView();
		model.setViewName("admin/subject-test");
		model.addObject("courseList", specialtyService.getCourseList());
		return model;
	}

	@ResponseBody
	@RequestMapping(value = "/getSubjectCourse", method = RequestMethod.GET)
	public List<SpecialtyInfo> courseList() {
		return specialtyService.getCourseList();
	}

	@ResponseBody
	@RequestMapping(value = "/getSubjectChapter/{cid}", method = RequestMethod.GET)
	public List<SpecialtyInfo> chapterList(@PathVariable("cid") Integer cid) {
		return specialtyService.getChapterList(cid);
	}
	@ResponseBody
	@RequestMapping(value = "/getSubjectPoints/{cid}", method = RequestMethod.GET)
	public List<SpecialtyInfo> pointsList(@PathVariable("cid") Integer cid) {
		return specialtyService.getPointsList(cid);
	}

	@RequestMapping(value = "/addSubject", method = RequestMethod.POST)
	public void addSubject(Subjectinfo subject, HttpServletResponse response) throws IOException {
		if (subject.getRightResult().split(",").length > 1) {
			subject.setSubjectType(2);
		} else {
			subject.setSubjectType(1);
		}
		if (subject.getRightResult().split(",").length == 1) {
			subject.setRightResult(subject.getRightResult().split(",")[0]);
		}
		if (subject.getOptionA().split(",").length > 1 && subject.getOptionA().split(",")[1] != null) {
			subject.setOptionA(subject.getOptionA().split(",")[1]);
			subject.setOptionB(subject.getOptionB().split(",")[1]);
			subject.setOptionC(subject.getOptionC().split(",")[1]);
			subject.setOptionD(subject.getOptionD().split(",")[1]);
			subject.setSubjectName(subject.getSubjectName().split(",")[1]);
		} else {
			subject.setOptionA(subject.getOptionA().split(",")[0]);
			subject.setOptionB(subject.getOptionB().split(",")[0]);
			subject.setOptionC(subject.getOptionC().split(",")[0]);
			subject.setOptionD(subject.getOptionD().split(",")[0]);
			subject.setSubjectName(subject.getSubjectName().split(",")[0]);
		}
		int row = subjectInfoService.addSucjects(subject);
		response.getWriter().print("试题添加成功!");
	}

	@RequestMapping(value = "/delSubject", method = RequestMethod.POST)
	public void delSubject(@RequestParam("subjectId") Integer subjectId, HttpServletResponse response)
			throws IOException {
		logger.info("删除试题 " + subjectId);

		int row = subjectInfoService.delSubject(subjectId);

		if (row > 0) {
			response.getWriter().print("t");
		} else {
			response.getWriter().print("f");
		}
	}

	@RequestMapping("/subject/{subjectId}")
	public ModelAndView updateSubject(@PathVariable("subjectId") Integer subjectId) {
		logger.info("修改试题 " + subjectId + " 的信息(获取试题信息)");
		Subjectinfo subject = subjectInfoService.getSubjectWithId(subjectId);
		ModelAndView model = new ModelAndView();
		String[] split = subject.getRightResult().split(",");
		if (subject.getSubjectType() == 1) {
			model.setViewName("admin/subject-test");
		} else {
			model.setViewName("admin/subject-test2");
		}
		model.addObject("subject", subject);
		model.addObject("a1", split[0]);
		if (split.length > 1 && split[1] != null) {
			model.addObject("a2", split[1]);
			if (split.length > 2 && split[2] != null) {
				model.addObject("a3", split[2]);
				if (split.length > 3 && split[3] != null) {
					model.addObject("a4", split[3]);
				} else {
					model.addObject("a4", null);
				}
			} else {
				model.addObject("a3", null);
				model.addObject("a4", null);
			}
		}
		return model;
	}

	@RequestMapping(value = "/updateSubject", method = RequestMethod.POST)
	public void updateSubject(Subjectinfo subject, HttpServletResponse response) throws IOException {
		logger.info("修改试题 " + subject.getSubjectId() + " 的信息(正式)");
		if (subject.getRightResult().split(",").length > 1) {
			subject.setSubjectType(2);
		} else {
			subject.setSubjectType(1);
		}
		if (subject.getRightResult().split(",").length == 1) {
			subject.setRightResult(subject.getRightResult().split(",")[0]);
		}
		if (subject.getOptionA().split(",").length > 1 && subject.getOptionA().split(",")[1] != null) {
			subject.setOptionA(subject.getOptionA().split(",")[1]);
			subject.setOptionB(subject.getOptionB().split(",")[1]);
			subject.setOptionC(subject.getOptionC().split(",")[1]);
			subject.setOptionD(subject.getOptionD().split(",")[1]);
			subject.setSubjectName(subject.getSubjectName().split(",")[1]);
		} else {
			subject.setOptionA(subject.getOptionA().split(",")[0]);
			subject.setOptionB(subject.getOptionB().split(",")[0]);
			subject.setOptionC(subject.getOptionC().split(",")[0]);
			subject.setOptionD(subject.getOptionD().split(",")[0]);
			subject.setSubjectName(subject.getSubjectName().split(",")[0]);
		}
		int row = subjectInfoService.updateSubject(subject);
		if (row > 0) {
			response.getWriter().print("试题修改成功!");
		} else {
			response.getWriter().print("试题修改失败!");
		}
	}

	@RequestMapping(value = "/importSubject", method = RequestMethod.GET)
	public ModelAndView importSubject() {
		ModelAndView model = new ModelAndView();
		model.setViewName("admin/importSubject");
		return model;
	}

	@RequestMapping(value = "/dispatcherUpload", method = RequestMethod.POST)
	public ModelAndView dispatcherUpload(HttpServletRequest request, @RequestParam("courseid") Integer courseid,
			@RequestParam("chapterid") Integer chapterid, @RequestParam("pointsid") Integer pointsid,
			@RequestParam("importOption") String importOption,
			@RequestParam("inputfile") MultipartFile excel) {
		ModelAndView model = new ModelAndView("reception/suc");
		String savePath = "";

		try {
			/** 保存上传 excel 文件 */
			System.out.println("Excel  ： "+excel);
			savePath = saveUploadFile(excel, request.getRealPath("/WEB-INF/upload"));

			/** 解析上传 excel 文件, 得到试题集合 */
			List<Subjectinfo> subjects = SubjectImportUtil.parseSubjectExcel(savePath, courseid, chapterid, pointsid);

			/** 只添加试题 */
			if ("0".equals(importOption)) {
				Map<String, Object> subjectsMap = new HashMap<String, Object>();
				subjectsMap.put("subjects", subjects);

				importSubejctOnly(subjects, subjectsMap);
			}
			if (subjects.size() == 0) {
				model.addObject("success",
						"操作处理失败，共添加 <b style='color:red;'>" + subjects.size() + "</b> 道题, 请检查上传数据正确性!");
			} else {
				model.addObject("success", "操作处理成功，共添加 " + subjects.size() + " 道题");
			}

		} catch (Exception e) {
			e.printStackTrace();
			model.setViewName("error");
			model.addObject("error", "上传失败, 请检查上传数据合理性或联系管理员!");
		} finally {
			/** 删除上传文件 */
			deleteUploadFile(savePath);
		}
		return model;
	}

	/**
	 * 删除上传文件
	 * 
	 * @param filePath 文件路径
	 */
	private void deleteUploadFile(String filePath) {
		File file = new File(filePath);

		if (file.exists()) {
			file.delete();
			logger.info("上传文件已被删除 " + filePath);
		}
	}
	/**
	 * 只将试题上传到数据库
	 * @param subjects
	 * @param subjectsMap
	 */
	private void importSubejctOnly(List<Subjectinfo> subjects, Map<String, Object> subjectsMap) {
		try {
			if (subjects != null && subjects.size() > 0) {
				//添加试题
				//int row = subjectInfoService.isAddSubjects(subjectsMap);
				for (Subjectinfo subjectinfo : subjects) {
					subjectinfo.setCourse(new SpecialtyInfo());
					subjectinfo.getCourse().setSpecialty_id(subjectinfo.getCourseid());
					subjectinfo.setChapter(new SpecialtyInfo());
					subjectinfo.getChapter().setSpecialty_id(subjectinfo.getChapterid());
					subjectinfo.setSpecialty(new SpecialtyInfo());
					subjectinfo.getSpecialty().setSpecialty_id(subjectinfo.getSpecialtyid());
					int addSucjects = subjectInfoService.addSucjects(subjectinfo);
				}
				logger.info("只将 excel 中的试题添加到数据库成功 SIZE "+subjects.size());
			} else {
				logger.info("上传试题文件中不存在试题，或解析失败");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 保存上传 excel 文件
	 * @param file 上传文件
	 * @return 保存路径
	 */
	private String saveUploadFile(MultipartFile file, String rootPath) {
		String fileName = file.getOriginalFilename();
		logger.info("保存上传文件 "+fileName+" 到 "+rootPath);
		
		try {
			file.transferTo(new File(rootPath+"/"+fileName));
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return rootPath+"/"+fileName;
	}
	/*
	 * 以下是蒋玉文的方法     有事找我
	 * */
	//作业选题的方法
	@ResponseBody
	@RequestMapping("xuanti")
	public Map<String, Object> xuantiList(Integer id,Integer page,Integer rows){
		List<Subjectinfo> kcSubList = subjectInfoService.kcSubList(id, (page-1)*rows, rows);
		long total = subjectInfoService.kcSubCount(id);
		
		System.out.println("试题总数======"+total);
		Map<String, Object> result = new HashMap<String, Object>();  
        result.put("total", total);  
        result.put("rows", kcSubList);
        result.put("page", page);
		return result;
	}
	//保存题目的方法
	@ResponseBody
	@RequestMapping("cunti")
	public List<Subjectinfo> getctList(Integer id){
		if (id!=null|| !("".equals(id))) {
			List<Subjectinfo> ctList = subjectInfoService.ctList(id);
			for (Subjectinfo subjectinfo : ctList) {
				myList.add(subjectinfo);
			}
		}
		
		return myList;
	}
	//从保存题目的list删除其中一条题目
	@ResponseBody
	@RequestMapping("/delcunti")
	public String delCunti(@Param("id")Integer id) {
		Subjectinfo remove=null;
		for (int i=0;i<myList.size() ;i++) {
			System.out.println("======"+myList.get(i));
			if (myList.get(i).getSubjectId()==id) {
				System.out.println(myList.get(i).getSubjectId()+"===id==="+id);
				 remove = myList.remove(i);
				i--;
			}
		}
		System.out.println("长度==="+myList.size());
		if (remove!=null) {
			System.out.println("不是null");
			return "1";
		}
		if (myList.size()==0) {
			return "3";
		}
		System.out.println("null");
		return "2";
		
		
	}
	
	//生成word文档的方法
	
	@RequestMapping("/shengword")//,String workdate,String zhangjie
	public String exportWord1( HttpSession session, HttpServletResponse response,
			HttpServletRequest request) throws IOException {
		System.out.println("jjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj");
		
		
		
		String wordName = request.getParameter("workname");
		String mysj = request.getParameter("mysj");
		
		String cla = request.getParameter("clazz");
		
		
		

		Configuration configuration = new Configuration();
		configuration.setDefaultEncoding("utf-8");
		Map<String, Object> dataMap = new HashMap<>();
		List<Map<String, Object>> table2 = new ArrayList<>();
		List<Map<String, Object>> urlList = new ArrayList<>();
		Map<String, String> checkUrl = new HashMap<>();

		
		  String url = request.getContextPath();

		Map<String, Object> m1 = new HashMap<>();
		
		
		System.out.println("word====="+myList.size());

		

		for (int i = 0; i < myList.size(); i++) {
			Subjectinfo sub= myList.get(i);

			

			Map<String, Object> map1 = new HashMap<>();

		
	

			Map<String, Object> map = new HashMap<>();
			String mapPath = "";

			
			map1.put("title", sub.getSubjectName()); // 题干
			
			if (sub.getSubjectType() == 1) {
				map1.put("type", "单选"); // 题目类型
			} else {
				map1.put("type", "多选"); // 题目类型
			}

		

			
			List<String> options = new ArrayList<>();
			if (myList.get(i).getOptionA()!=null) {
				options.add("A:"+myList.get(i).getOptionA());
			}
			if (myList.get(i).getOptionB()!=null) {
				options.add("B:"+myList.get(i).getOptionB());			
			}
			if (myList.get(i).getOptionC()!=null) {
				options.add("C:"+myList.get(i).getOptionC());
			}
			if (myList.get(i).getOptionD()!=null) {
				options.add("D:"+myList.get(i).getOptionD());
			}
			if (myList.get(i).getOptionE()!=null) {
				options.add("D:"+myList.get(i).getOptionE());
			}
			if (myList.get(i).getOptionF()!=null) {
				options.add("D:"+myList.get(i).getOptionF());
			}
			System.out.println(options.toString()+" LLLL");
			map1.put("options", options);
			
			
			table2.add(map1);
		}

	
		dataMap.put("table2", table2);
		dataMap.put("path2", urlList);
		// 设置模本装置方法和路径,FreeMarker支持多种模板装载方法。可以重servlet，classpath，数据库装载，
		// 这里我们的模板是放在com.havenliu.document.template包下面
		configuration.setClassForTemplateLoading(this.getClass(), "/model/"); // 这个路径自己随便建一个就行了
		Template t = null;
		Writer out = null;
		File outFile = null;
		String name=null;
		try {
			t = configuration.getTemplate("word.ftl");
			 name = request.getServletContext().getRealPath("/target/uploads/") + wordName+ ".docx";
			outFile = new File(name);
			out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"));
			t.process(dataMap, out);
		} catch (Exception e) {
			e.printStackTrace();
		} finally { 
			if (out != null) {
				try {
					out.flush();
					out.close();
				} catch (Exception e2) {
					e2.printStackTrace();
				}
			}
		}
		
		//name   路径
		
		Users user=(Users) request.getSession().getAttribute("user");
		
		ClassInfo clazz=new ClassInfo();
		clazz.setClazz_id(Integer.parseInt(cla));
		
		
		
		long addWork = ws.addWork(wordName, mysj, clazz, name,user);
		System.out.println("nnnnnnnn===="+addWork);
		
		/*
		 * // 导出做准备的 request.setCharacterEncoding("UTF-8"); File file = null;
		 * InputStream fin = null; ServletOutputStream out1 = null; try { fin = new
		 * FileInputStream(outFile); response.setCharacterEncoding("utf-8");
		 * 
		 * response.setContentType("application/msword"); //
		 * 设置浏览器以下载的方式处理该文件默认名为Exhibition.doc String fileName2 =
		 * URLEncoder.encode(wordName + ".docx", "utf-8");
		 * response.setHeader("content-disposition","attachment;filename=" + fileName2);
		 * System.out.println("333333333"); out1 = response.getOutputStream(); byte[]
		 * buffer = new byte[1024]; // 缓冲区 int bytesToRead = -1; //
		 * 通过循环将读入的Word文件的内容输出到浏览器中 while ((bytesToRead = fin.read(buffer)) != -1) {
		 * out1.write(buffer, 0, bytesToRead); System.out.println("222222222"); } }
		 * finally { if (fin != null) fin.close(); if (out1 != null) out1.close(); if
		 * (outFile != null) outFile.delete(); // 删除临时文件 }
		 */
		myList=null;
		return "redirect:teachercurr";
	}
}
